<?php
/**
 * Created by PhpStorm.
 * User: ^2_3^王尔贝
 * Date: 2020/7/13
 * Time: 13:53
 */

namespace app\exception;

use think\exception\Handle;
use think\exception\HttpException;
use think\exception\ValidateException;
use think\Response;
use Throwable;

/**
 * 自定义异常处理
 * Class Http
 *
 * //// 绑定自定义异常处理handle类( provider.php )
 * 'think\exception\Handle'       => '\\app\\exception\\Http',
 *
 * @package app\common\exception
 * @author ^2_3^王尔贝
 */
class HttpHandle extends Handle
{
    public function render($request, Throwable $e): Response
    {
        // 参数验证错误
        if ($e instanceof ValidateException) {
            return json('[自定义异常处理] '.$e->getError(), 422);
        }

        // 请求异常
        if ($e instanceof HttpException && $request->isAjax()) {
            return response($e->getMessage(), $e->getStatusCode());
        }

        // 其他错误交给系统处理
        return parent::render($request, $e);
    }

}